package com.nq.controller;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.nq.common.LoginType;
import com.nq.common.ServerResponse;
import com.nq.dao.UserMapper;
import com.nq.pojo.SiteSmsLog;
import com.nq.service.ISiteSmsLogService;
import com.nq.service.ISmsService;
import com.nq.service.IUserService;
import com.nq.utils.DateTimeUtil;
import com.nq.utils.email.SendHTMLMail;
import com.nq.utils.redis.RedisShardedPoolUtils;
import com.nq.utils.smsUtil.AbroadSmsUtil;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Controller
@RequestMapping({"/api/sms/"})
public class SmsApiController {
    private static final Logger log = LoggerFactory.getLogger(SmsApiController.class);

    @Value("${sms.template.reg}")
    private String reg;

    @Value("${sms.template.forget_pwd}")
    private String forgetPwd;

    @Autowired
    ISmsService iSmsService;

    @Autowired
    ISiteSmsLogService iSiteSmsLogService;

    @Resource
    AbroadSmsUtil abroadSmsUtil;

    @Resource
    UserMapper userMapper;

    @Autowired
    private SendHTMLMail sendHTMLMail;


    /**
     * 注册用户 短信发送
     * @param phoneNum
     * @return
     */
    @RequestMapping({"sendRegSms.do"})
    @ResponseBody
    public ServerResponse<String> sendRegSms(String code, String phoneNum) {
        if (StrUtil.isBlank(code) || StrUtil.isBlank(phoneNum)) {
            return ServerResponse.createByErrorMsg("手机号或验证码不能为空");
        }
        // 判断手机号是否存在，如果存在则给出提示
        val byPhone = userMapper.findByPhone(code, phoneNum);
        if (null != byPhone) {
            return ServerResponse.createByErrorMsg("手机号已存在，请直接登录");
        }

        try {
            String key = "V_PHONE_CODE_" + code + "_" + phoneNum;
            String value = RandomUtil.randomNumbers(6);
//            String content = String.format(reg, value);
//            String result = abroadSmsUtil.sendSms(code + phoneNum, content);
//            log.info("短信发送请求: {}, {}", code + phoneNum, result);
//            JSONObject obj = JSONUtil.parseObj(result);
//            if ("9999".equals(obj.getStr("code"))) {
//                RedisShardedPoolUtils.setEx(key, value, 300);
//                sendHTMLMail.saveSiteSmsLog(code + phoneNum, LoginType.PHONE.getCode(), value, "注册验证码");
//                return ServerResponse.createBySuccess("Send successful!");
//            }
            value = "9999";
            RedisShardedPoolUtils.setEx(key, value, 3000);
            return ServerResponse.createByErrorMsg("发送成功");
        } catch (Exception e) {
            log.error("请求发送短信异常", e);
            return ServerResponse.createByErrorMsg("请求发送短信异常");
        }
    }


    /**
     * 找回密码 短信发送
     * @param phoneNum
     * @return
     */
    @RequestMapping({"sendForgetSms.do"})
    @ResponseBody
    public ServerResponse sendForgetSms(String code, String phoneNum) {
        if (StrUtil.isBlank(phoneNum)) {
            return ServerResponse.createByErrorMsg("Sending failed, phone number cannot be empty.");
        }
        // 判断手机号是否存在，如果不存在则给出提示
        val byPhone = userMapper.findByPhone(code, phoneNum);
        if (null == byPhone) {
            return ServerResponse.createByErrorMsg("Sending failed, phone number does not exist.");
        }

        log.info("找回密码发送短信：{},{}",code, phoneNum);
        String key = "V_FORGET_PHONE_CODE_" + code + "_" + phoneNum;
        String value = RandomUtil.randomNumbers(6);
        RedisShardedPoolUtils.setEx(key, value, 300);
        return ServerResponse.createBySuccessMsg("发送成功");
//        String content = String.format(forgetPwd, value);
//        String result = abroadSmsUtil.sendSms(code + phoneNum, content);
//        log.info("短信发送请求: {}, {}", code + phoneNum, result);
//        JSONObject obj = JSONUtil.parseObj(result);
//        if ("9999".equals(obj.getStr("code"))) {
//            RedisShardedPoolUtils.setEx(key, value, 300);
//            sendHTMLMail.saveSiteSmsLog(code + phoneNum, LoginType.PHONE.getCode(), value, "找回密码，短息验证码");
//            return ServerResponse.createBySuccessMsg("发送成功");
//        } else {
//            return ServerResponse.createByErrorMsg("短信发送失败，请重试");
//        }
    }


}
